package org.aileen.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {
    //设置令牌的过期时间:30分钟:
    private static long expiration = 30 * 60 * 1000L; //30min

    //key
    private static String secretString = "37hG0gZaKIVdP2iCnV8EoapeWHCgXZ/CXlq0rRUqBF4";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode( secretString ));


    //生成令牌Token
    public static String genJwt(Map<String, Object> claims) {



        //写死的左侧用户信息主页
//        Map<String,Object> data = new HashMap<>();
//        data.put("id",1);
//        data.put("name","aileen");

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration)) //设置过期时间
                .signWith(key)
                .compact();

    }

    //效验
    public static Claims verify(String token){
        //使用JWT内部提供的方法来校验
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        //如果token不合法,会抛出异常
        try{
           claims =  build.parseClaimsJws(token).getBody();
        }catch(ExpiredJwtException e){
            log.error("Token过期 , 验证失败 , 其值为: {}", token);
        }catch(Exception e){
            log.error("Token不合法 , 验证失败 , 其值为: {}", token);
        }

        return claims;

    }

    //从Token中获取用户Id
    public static Integer getUserIdFromToken(String token) {
        //检验token的合法性
        Claims claims = verify(token);
        Assert.notNull(claims, "Token不合法");
        //从claims中获取用户id
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
